use serde::Serialize;
use reqwest::Client;
use webrtc::ice_transport::ice_candidate::RTCIceCandidate;
use crate::api::get_stream_token::get_stream_token;
use crate::api::get_session_id::get_session_id;
use webrtc::ice_transport::ice_candidate::RTCIceCandidateInit;
use anyhow::{Result, anyhow};

#[derive(Serialize)]
struct IceCandidatePayload {
    candidate: String,
    sdp_mid: Option<String>,
    sdp_mline_index: Option<u16>,
}

#[derive(Serialize)]
struct IceCandidatesRequest {
    iceCandidates: Vec<IceCandidatePayload>,
}

pub async fn send_ice(ice_candidates: Vec<RTCIceCandidate>) -> Result<()>{

    let url = format!("https://uks.core.gssv-play-prodxhome.xboxlive.com/v5/sessions/home/{}/ice", get_session_id(None).await.unwrap());
    let client = Client::new();
    let Authorization = format!("Bearer {}", get_stream_token().await.unwrap());

    let payload = {
        let cache = ice_candidates;
        let cache:Vec<RTCIceCandidateInit> = cache.iter().map(|c| {
            return c.to_json().unwrap();
        }).collect();
        let candidates: Vec<IceCandidatePayload> = cache.iter().map(|c| IceCandidatePayload {
            candidate: c.candidate.clone(),
            sdp_mid: c.sdp_mid.clone(),
            sdp_mline_index: c.sdp_mline_index,
        }).collect();

        IceCandidatesRequest { iceCandidates: candidates }
    };
    let response = client.post(url)
        .header("Accept", "application/json")
        .header("Content-Type", "application/json")
        .header("Authorization", Authorization)
        .json(&payload)
        .send().await?;
    let response_code = response.status().as_u16();
    if (response_code < 200 || response_code > 299) {
        return Err(anyhow!("Failed to send ICE candidates. Response code: {response_code}"));
    }
    return Ok(());
}